#ifndef THUNDERRAID_GAMEVIEW_H
#define THUNDERRAID_GAMEVIEW_H


#include <QWidget>
#include <chrono>
#include <QMediaPlayer>
#include "gamelevel.h"

class GameItem;
class Plane;
class Bullet;
class QLCDNumber;

class LabeledNumber;

class GameView :public QWidget{
    static constexpr int GAME_WIDTH = 512;
    static constexpr int GAME_HEIGHT = 768;
    static constexpr qreal GAME_MAP_SPEED = 0.25;

    Q_OBJECT
public:
    enum State{
        RUNNING, PAUSE, FINISHED
    };
    explicit GameView(QWidget *parent = nullptr);
    ~GameView() override;

    void applyToSetLevel(const GameLevel& level);
    void setLevel(const GameLevel &level);

    void addItem(GameItem *item);
    void removeItem(GameItem *item);
    void addHeroBullet(Bullet *bullet);
    void addEnemyBullet(Bullet *bullet);

    void success();
    void failed();
    [[nodiscard]] int getScore() const;
    void setScore(int score);

    QString currentLevelId() const;

signals:
    void wantChangeLevel(const GameLevel &level);
    void gameFinished(bool isSuccess, int score);
    void gamePause();

protected:
    void paintEvent(QPaintEvent *event) override;

public slots:

    void init();
    void reset();
    void start();
    void end();
    void pause();

    void updateGame();
    void saveGame() const;
    void loadSave();


protected:
    void checkCollides();
    void handleOutRangeItem();
    void addEnemy(qreal interval);
    void addEnemyToView(EnemyPlane *plane);
    void updateOil(qreal interval);

    void keyReleaseEvent(QKeyEvent *event) override;
    void keyPressEvent(QKeyEvent *event) override;

private:
    QSoundEffect bgm;
    bool gameEnd;
    QPixmap map;
    GameLevel level;
    qreal map_pos = 0;
    QTimer *update_timer;
    std::chrono::time_point<std::chrono::steady_clock> prev_update;
    qreal interval_ms{};

    QList<GameItem *> items;

    int hp = 500;
    int oil = 100;
    int score = 0;

    Plane *hero = nullptr;
    bool forward = false, backward = false, left = false, right = false;

    qreal addEnemyIntervalCount = 0;
    QList<Plane *> enemies{};
    QList<Bullet *> enemies_bullets{}, hero_bullets{};

    LabeledNumber *hp_number, *oil_number, *score_number;
};


#endif//THUNDERRAID_GAMEVIEW_H
